package com.example.edu.tips;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class WordManageServiceImpl extends AbstractWordManage implements IWordManageService {

    @Override
    public List<Node> searchPrefix(String prefix) {
        Node root = wordsTree;
        char[] chars = prefix.toCharArray();
        StringBuilder sb = new StringBuilder();

        for (char aChar : chars) {
            int charIndex = chargeIndex(aChar);
            if (charIndex > root.slot.length || charIndex < 0 || root.slot[charIndex] == null) {
                return Collections.emptyList();
            }
            sb.append(aChar);
            root = root.slot[charIndex];
        }

        ArrayList<Node> list = new ArrayList<>();
        if (root.prefix != 0) {
            collect(root, sb.toString(), list, RESULT_LIMIT);
        }
        return list;
    }
}
